package com.rytong.tools.utils;

import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;

public class AsyncImageLoader {
	//弱引用，当内存不足时，会主动清理部分弱引用
	public WeakHashMap<String,Bitmap> cacheMap = new WeakHashMap<String, Bitmap>(100);
	//正常图片，不做任何处理
	private static final int TYPE_NORMAL = 0;
	//做圆角图片处理
	private static final int TYPE_ROUND_CORNER = 1;
	//线程池
	private ExecutorService executorService = Executors.newFixedThreadPool(3);
	// 缓存图片类
	public CacheBitmapUtils cacheUtils = null;

	private Handler handler = null;
	public AsyncImageLoader() {
		if (null == cacheUtils) {
			cacheUtils = new CacheBitmapUtils();
		}
		
		if(null == handler){
			handler = new Handler();
		}
	}

	/**
	 * LPImageItem 下载图片
	 * @param context
	 * @param view
	 * @param url
	 */
	public void downloadImage(Context context,final String url,final ImageCallBack1 callback){
		if (url == null || "".equalsIgnoreCase(url)) {
			return;
		}
		final Drawable drawable = HttpUtils.loadImageFromUrl(url);
		if(null != drawable){
			//加入消息队列
			handler.post(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					callback.loadImageSuccess(drawable);
					cacheUtils.cacheBitmap(((BitmapDrawable)drawable).getBitmap(), url);
				}
			});
		}
	}

	/**
	 * 绑定网络图片
	 * 
	 * @param context
	 * @param view
	 * @param url
	 * @param resourceId
	 *            等待图片id
	 * @param type 图片类型
	 */
	public void displayView(final Context context, final View view, final String url,
			final int resourceId,final int type) {
		if (null == view || url == null || "".equalsIgnoreCase(url)) {
			return;
		}
		
		if(!cacheUtils.isInCache(url)){
			if (resourceId > 0) {
				if (Thread.currentThread().getId() == 1) {
					view.setBackgroundResource(resourceId);
				} else{
					((Activity)context).runOnUiThread(new Runnable() {
						@Override
						public void run() {
							view.setBackgroundResource(resourceId);
						}
					});
				}
			}
		}
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Bitmap bitmap = getBitmapFromCache(url);
				if(null == bitmap){
					bitmap = getBitmap(context,url);					
				}
				setViewBitmap(context, view, bitmap, type);
			}
		});
	}
	
	/**
	 * 下载图片不做绑定视图,针对电影票
	 * @param url
	 * @param callback
	 */
	public void downloadBitmap(final Context context,final String url,final ImageCallBack callback){
		boolean isExit = cacheUtils.isInCache(url);
		if(isExit || !HttpUtils.is_Intent(context)){
			return ;
		}
		
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				final Bitmap bitmap = getBitmap(context,url);
				if(null != bitmap){
					//加入消息队列
					handler.post(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							if(!cacheMap.containsKey(url)){
								cacheMap.put(url, bitmap);
							}
							if(callback != null){
								callback.loadImageSuccess(bitmap, url);					
							}
						}
					});
				}
			}
		});
	}
	
	/**
	 * 获取图片，主要针对电影票,先从map中获取，如果没有然后再从本地获取
	 * @param url
	 * @return
	 */
	public Bitmap getBitmapFromCache(String url){
		Bitmap bitmap = cacheMap.get(url);
		if(bitmap == null){
			bitmap = cacheUtils.getCacheBitmap(url);
			if(cacheMap.containsKey(url)){
				cacheMap.put(url, bitmap);				
			}
		}
		return bitmap;
	}
	/**
	 * 从网络获取图片并缓存
	 * @param url
	 */
	public Bitmap getBitmap(Context context,String url){
		Bitmap bitmap = null;
		if(HttpUtils.is_Intent(context)){
			bitmap = HttpUtils.downloadBitmap(url);
			if(null != bitmap){
				cacheUtils.cacheBitmap(bitmap, url);
			}
		}
		return bitmap;
	}
	
	/**
	 * 将图片绑定到试图上
	 * @param view
	 * @param bitmap
	 */
	public void setViewBitmap(Context context,final View view ,Bitmap bitmap,int type){
		if(view == null || bitmap == null){
			Utils.printOutToConsole("bitmap is null");
			return ;
		}
		
		if(type == TYPE_NORMAL){
			//正常不作处理
		} else if(type == TYPE_ROUND_CORNER){
			bitmap = Utils.toRoundCorner(bitmap, context);
		}
		
		final Bitmap temp = bitmap;
		if (Thread.currentThread().getId() == 1) {
			if(view instanceof ImageView){
				((ImageView)view).setImageBitmap(temp);
			}else{
				view.setBackgroundDrawable(new BitmapDrawable(temp));
			}
		} else{
			((Activity)context).runOnUiThread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					if(view instanceof ImageView){
						((ImageView)view).setImageBitmap(temp);
					}else{
						view.setBackgroundDrawable(new BitmapDrawable(temp));
					}
				}
			});
		}
	}
	
	/**
	 * 下载图片的回调函数
	 * AsyncImageLoader.java
	 *
	 * @author cheng.l 2013-8-3
	 */
	public interface ImageCallBack{
		public void loadImageSuccess(Bitmap bitmap ,String url);
	}
	
	public interface ImageCallBack1{
		public void loadImageSuccess(Drawable drawable);
	}
}
